﻿var VK = {
    _xdType: 0, // 1 - postMessage, 2 - flash proxy
    _lcName: '',
    params: {},
    init: function (success, failure) {
        if (!parent) return false;
        this._lcName = window.name;
        var self = this;
        window.vk_onConnectionInit = function () {
            if (self.isFunc(success)) success();
        };
        window.vk_onConnectionFail = this.isFunc(failure) ? failure : function () { };
        this.initXDConn();
    },
    loadParams: function (q) {
        if (typeof q == 'Object') this.params = q;
        else {
            var tmp = q.substr(q.indexOf('?') + 1).split('&');
            for (var i in tmp) {
                var v = tmp[i].split('=');
                this.params[v[0]] = decodeURIComponent(v[1]);
            }
        }
    },
    initXDConn: function () {
        if (parent.postMessage) {
            this._xdType = 1;
            var cb = function () { VK._runCallback.apply(VK, arguments) };
            if (window.addEventListener)
                window.addEventListener('message', cb, false);
            else if (window.attachEvent)
                window.attachEvent('onmessage', cb);
            var self = this;
            setTimeout(function () {
                self.callMethod('setAppReady');
                window.vk_onConnectionInit();
            }, 0);
        } else if (this._lcName) {
            if (typeof SWFObject != 'undefined') {
                this._initFConn();
            }
            this.addScript('http://vk.com/js/lib/swfobject.js');
            var timer = setInterval(function () {
                if (typeof SWFObject != 'undefined') {
                    clearInterval(timer);
                    VK._initFConn();
                } 
            }, 100);
        } else {
            setTimeout(window.vk_onConnectionFail, 0);
        }
    },
    addScript: function (url) {
        var el = document.createElement('script');
        el.type = 'text/javascript';
        el.src = url;
        document.getElementsByTagName('head')[0].appendChild(el);
    },
    callMethod: function (method) {
        var args = Array.prototype.slice.call(arguments);
        if (this._xdType == 1) {
            parent.postMessage(args.join(String.fromCharCode(31)), "*");
        } else if (this._xdType == 2) {
            var r = [], arr = args.slice(1);
            for (var i in arr) {
                r.push(typeof arr[i] == 'string' ? "'" + arr[i].replace(/'/g, "\\'") + "'" : this.intVal(arr[i]));
            }
            eval("this._xdf." + method + "(" + r.join(',') + ");");
        }
    },
    _callbacks: {},
    addCallback: function (name, callback) {
        if (callback) this._callbacks[name] = callback;
    },
    removeCallback: function (name, callback) {
        if (this._callbacks[name] == callback) delete this._callbacks[name];
    },
    isFunc: function (obj) {
        return Object.prototype.toString.call(obj) === "[object Function]";
    },
    intVal: function (num) {
        var r = parseInt(num);
        return isNaN(r) ? 0 : r;
    },
    boolVal: function (val) {
        return Boolean(val) ? 1 : 0;
    },
    _runCallback: function (e) {
        var method, args;
        if (typeof e == 'object') {
            args = e.data.split(String.fromCharCode(31));
        } else {
            args = Array.prototype.slice.call(arguments);
        }
        method = args.shift();
        if (method && this.isFunc(this._callbacks[method]))
            this._callbacks[method].apply(null, args);
    },
    _initFConn: function () {
        window.vk_runCallback = function () { VK._runCallback.apply(VK, arguments) };
        var el = document.createElement('span');
        el.id = 'vk_xd_connection_wrap';
        el.style.position = 'absolute';
        el.style.marginTop = '-10px';
        document.body.appendChild(el);

        var so = new SWFObject('http://vk.com/swf/xd_connector.swf', 'vk_xd_connection', "1", "1", '9');
        so.addParam('allownetworking', 'all');
        so.addParam('allowscriptaccess', 'always');
        so.addVariable('lc_name', this._lcName);
        if (so.write('vk_xd_connection_wrap')) {
            this._xdf = document.getElementById('vk_xd_connection');
            this._xdType = 2;
        } else {
            window.vk_onConnectionFail();
        }
    }
}

VK.External = {
    showPaymentBox: function (votes) {
        VK.callMethod('showPaymentBox', VK.intVal(votes));
    },
    showSettingsBox: function (settings) {
        VK.callMethod('showSettingsBox', settings);
    },
   showMerchantPaymentBox: function (params){
        VK.callMethod('showMerchantPaymentBox', params);
    },
    showInstallBox: function () {
        VK.callMethod('showInstallBox');
    },
    showInviteBox: function () {
        VK.callMethod('showInviteBox');
    },
    resizeWindow: function (width, height) {
        VK.callMethod('resizeWindow', VK.intVal(width), VK.intVal(height));
    },
    scrollWindow: function (scrollTop, speed) {
        VK.callMethod('scrollWindow', VK.intVal(scrollTop), VK.intVal(speed));
    },
    setLocation: function (location, fireEvent) {
        VK.callMethod('setLocation', location, VK.boolVal(fireEvent));
    },
    setTitle: function (title) {
        VK.callMethod('setTitle', title);
    },
    saveWallPost: function (hash) {
        VK.callMethod('saveWallPost', hash);
    },
    showProfilePhotoBox: function (hash) {
        VK.callMethod('showProfilePhotoBox',hash);
    }
}